"use client"

import { useState } from "react"
import { DataTable } from "@/components/common/data-table"
import { Button } from "@/components/ui/button"
import { Track } from "@/types/admin"
import { Plus } from "lucide-react"
import { columns } from "./columns"
import { TrackDialog } from "@/components/admin/track-dialog"
import { DeleteDialog } from "@/components/admin/delete-dialog"
import { useAdminStore } from "@/lib/store"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"

export default function TracksPage() {
  const { tracks, deleteTrack } = useAdminStore()
  
  const [openAddEditDialog, setOpenAddEditDialog] = useState(false)
  const [openDeleteDialog, setOpenDeleteDialog] = useState(false)
  const [selectedTrack, setSelectedTrack] = useState<Track | undefined>(undefined)

  const handleAddTrack = () => {
    setSelectedTrack(undefined)
    setOpenAddEditDialog(true)
  }

  const handleEditTrack = (track: Track) => {
    setSelectedTrack(track)
    setOpenAddEditDialog(true)
  }

  const handleDeleteClick = (track: Track) => {
    setSelectedTrack(track)
    setOpenDeleteDialog(true)
  }

  const handleConfirmDelete = () => {
    if (selectedTrack) {
      deleteTrack(selectedTrack.id)
      setOpenDeleteDialog(false)
    }
  }

  return (
    <div className="space-y-6">
      <Card className="card-shadow">
        <CardHeader className="flex flex-row items-center justify-between pb-2">
          <CardTitle className="text-xl font-bold">股道管理</CardTitle>
          <Button 
            onClick={handleAddTrack}
            className="rounded-lg bg-primary hover:bg-primary/90"
          >
            <Plus className="mr-2 h-4 w-4" /> 新增股道
          </Button>
        </CardHeader>
        <CardContent>
          <p className="text-muted-foreground mb-4">管理车辆段内的所有股道信息。</p>
          <DataTable 
            columns={columns({ 
              onEdit: handleEditTrack, 
              onDelete: handleDeleteClick 
            })} 
            data={tracks}
            searchPlaceholder="搜索股道(支持股道名称、编号、类型、状态等)"
          />
        </CardContent>
      </Card>

      <TrackDialog
        open={openAddEditDialog}
        onOpenChange={setOpenAddEditDialog}
        track={selectedTrack}
      />

      <DeleteDialog
        open={openDeleteDialog}
        onOpenChange={setOpenDeleteDialog}
        onConfirm={handleConfirmDelete}
        title="删除股道"
        description={`确定要删除股道 "${selectedTrack?.name}" 吗？此操作不可撤销。`}
      />
    </div>
  )
} 